<template>
  <div class="app-container">
     <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px">
        <el-form-item label="系统列表" prop="roleName" label-width="120px">
          <el-select v-model="value" placeholder="无登录系统" size="large"  suffix-icon="Switch" style="width: 260px" @change="changeValue">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
        </el-form-item>
        <div>
          <el-form-item label="用户名称" prop="name" label-width="120px">
           <el-input
              v-model="queryParams.name"
              placeholder="请输入用户名称"
              clearable
              style="width: 260px"
              @keyup.enter="handleQuery"
               @clear="handleQuery"
               @input="handleInput"
           />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
        </div>
     </el-form>
     <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
           <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-if="value"
           >新增</el-button>
        </el-col>
        <el-col :span="1.5">
           <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:role:edit']"
           >修改</el-button>
        </el-col>
        <el-col :span="1.5">
           <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:role:remove']"
           >删除</el-button>
        </el-col>
        <el-col :span="1.5">
           <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['system:role:export']"
           >导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
     </el-row>

     <!-- 表格数据 -->
     <el-table v-loading="loading" size="large" :data="roleList" :max-height="tableHeight" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column type="index" label="序号" align="center" width="200">
          <template #default="scope">
            <span>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="角色名称" prop="name" align="center" width="200" />
        <el-table-column label="角色等级:0~9（高~低）" align="center" prop="level" width="300" />
        <!-- <el-table-column label="系统名称" prop="tenantDes" width="500" /> -->
        <el-table-column label="系统名称" width="400" align="center">
          <template #default="scope">
            <span>{{ getTenantName(scope.row.systemID) }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作"  align="center" min-width="160px" class-name="small-padding fixed-width">
           <template #default="scope">
             <!-- <el-tooltip content="修改" placement="top" > -->
               <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
             <!-- </el-tooltip> -->
               <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
           </template>
        </el-table-column>
     </el-table>

     <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
     />

     <!-- 添加或修改角色配置对话框 -->
     <el-dialog :title="title" v-model="open" width="800px" append-to-body>
        <el-form ref="roleRef" :model="form" :rules="rules" label-width="200px">
           <el-form-item label="角色名称" prop="name" required>
              <el-input v-model="form.name" placeholder="请输入角色名称" />
           </el-form-item>
           <el-form-item label="角色等级:0~9（高~低）" :required="true" prop="level">
              <el-input-number v-model="form.level" controls-position="right" :min="0" :max="9" @change="handleChange" @blur="handleChange" />
           </el-form-item>
           <el-form-item label="菜单权限" v-if="form.id">
               <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
               <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
               <!-- <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox> -->
               <el-tree
                  class="tree-border"
                  :data="menuOptions"
                  show-checkbox
                  ref="menuRef"
                  node-key="id"
                  empty-text="暂无数据"
                  :check-strictly="checkStrictly"
                  :default-expanded-keys="form.checkedIds"
                  :default-checked-keys="form.checkedIds"
                  :props="{ label: 'reName', children: 'children' }"
               ></el-tree>
            </el-form-item>
        </el-form>
        <template #footer>
           <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
           </div>
        </template>
     </el-dialog>
  </div>
</template>

<script setup name="Role">
import { useInfoStore } from '@/store/modules/info.js'
const tableHeight = ref(document.documentElement.scrollHeight - 280 + "px");

const userInfo = useInfoStore();

const router = useRouter();
const { proxy } = getCurrentInstance();
// const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const roleList = ref([]);
const open = ref(false);
const checkStrictly = ref(true);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const menuOptions = ref([]);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const deptExpand = ref(true);
const deptNodeAll = ref(false);
const deptOptions = ref([]);
const openDataScope = ref(false);
const menuRef = ref(null);
const deptRef = ref(null);
const value = ref('')
const options = ref([])
const data = reactive({
 form: {
   name: null,
   level: 9,
   id: null,
   checkedIds:[],
 },
 queryParams: {
   pageNo: 1,
   pageSize: 10,
   name: null,
   tenantID:null
 },
 rules: {
    name: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
    level: [{ required: true, message: "角色等级不能为空", trigger: "blur" }],
 },
});

const { queryParams, form, rules } = toRefs(data);


// const handleCheckChange = () => {
//   let checkedNodes = menuRef.value.getCheckedNodes(false,false);
// };

/** 查询角色列表 */
async function getList() {  
   loading.value = true;
// 先查询系统列表
  const data = await proxy.API.GetTenantList({tenantname:null});
  if(data.code===1 && data?.data?.length>0){
    options.value = data.data.map(item => {
      return { value: item.id, label: item.tenantName }
    })
    // 默认选择第一个系统
    value.value = value.value?value.value:options.value[0].value;
    queryParams.value.tenantID = queryParams.value.tenantID?queryParams.value.tenantID:options.value[0].value;
    proxy.API.GetRolePageList(queryParams.value).then(response => {
        roleList.value = response.data.list;
        total.value = response.data.total;
        loading.value = false;
    });
  }else{
     loading.value = false;
     proxy.$modal.msgError("当前还没有系统，请先添加系统");
  }
  
}
// 角色反查租户系统
function getTenantName(id){
  const item = options.value.filter(item =>{
    return item.value === id;
  });
  const name = item.length>0?item[0].label:null;
  return name;
}

// 处理值变化的方法
const handleChange = (value) => {
  if (Number.isInteger(value)) {
    if (value < 0) {
      form.value.level = 0;
    } else if (value > 9) {
      form.value.level = 9;
    }
  } else {
    // 如果不是整数，恢复到上一个有效值
    form.value.level = Math.round(form.value.level);
  }
}


// 切换系统
function changeValue(val){
  value.value = val;
  queryParams.value.tenantID = val;
  getList();
} 

// 输入时触发的防抖处理函数
let timer = null;
function handleInput() {
    clearTimeout(timer);
    timer = setTimeout(handleQuery, 300);
}

/** 搜索按钮操作 */
function handleQuery() {
 queryParams.value.pageNo = 1;
 getList();
}

/** 重置按钮操作 */
function resetQuery() {
 dateRange.value = [];
 proxy.resetForm("queryRef");
 handleQuery();
}

/** 删除按钮操作 */
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除用户"' + row.name + '"的数据项?').then(function () {
    proxy.API.DelRole({id:row.id}).then(response => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    });
  })
}

/** 导出按钮操作 */
function handleExport() {
 proxy.download("system/role/export", {
   ...queryParams.value,
 }, `role_${new Date().getTime()}.xlsx`);
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
 ids.value = selection.map(item => item.roleId);
 single.value = selection.length != 1;
 multiple.value = !selection.length;
}

/** 角色状态修改 */
function handleStatusChange(row) {
 let text = row.status === "0" ? "启用" : "停用";
 proxy.$modal.confirm('确认要"' + text + '""' + row.roleName + '"角色吗?').then(function () {
   return changeRoleStatus(row.roleId, row.status);
 }).then(() => {
   proxy.$modal.msgSuccess(text + "成功");
 }).catch(function () {
   row.status = row.status === "0" ? "1" : "0";
 });
}

/** 更多操作 */
function handleCommand(command, row) {
 switch (command) {
   case "handleDataScope":
     handleDataScope(row);
     break;
   case "handleAuthUser":
     handleAuthUser(row);
     break;
   default:
     break;
 }
}

/** 分配用户 */
function handleAuthUser(row) {
 router.push("/system/role-auth/user/" + row.roleId);
}

/** 查询菜单树结构 */
function getMenuTreeselect(row) {
 proxy.API.GetResourceList({
      reName: "",
      rePath: "",
      reParetntID: -1,//查询全部路由
      tenantID: value.value
    }).then(response => {
         response.data.forEach(element => {
            element.children = [];
         });
        menuOptions.value = proxy.handleTree(response.data);
        loading.value = false;
        GetRoleMenuList(row);
    });
}

/** 所有部门节点数据 */
function getDeptAllCheckedKeys() {
 // 目前被选中的部门节点
 let checkedKeys = deptRef.value.getCheckedKeys();
 // 半选中的部门节点
 let halfCheckedKeys = deptRef.value.getHalfCheckedKeys();
 checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
 return checkedKeys;
}

/** 重置新增的表单以及其他数据  */
function reset() {
 if (menuRef.value != undefined) {
   menuRef.value.setCheckedKeys([]);
 }
 form.value = {
   name: null,
   level: 9,
   id: null,
   checkedIds:[]
 };
 menuNodeAll.value = false;
 menuExpand.value = false;

 proxy.resetForm("roleRef");
}

/** 添加角色 */
function handleAdd() {
 reset();
 open.value = true;
 title.value = "添加角色";
}

/** 修改角色 */
async function handleUpdate(row) {
 reset();
 getMenuTreeselect(row);
 Object.keys(form.value).forEach(key => {
   form.value[key] = row[key];
   if(form.value[key]==undefined){
     form.value[key]=null
   }
 });
 open.value = true;
 title.value = "修改角色";
}


/** 根据角色ID查询菜单树结构 */
function GetRoleMenuList(row) {
  checkStrictly.value = true; //默认展示开启
  return  proxy.API.GetRoleMenuList({
    resourcesID:-1,
    roleID:row.id,
  }).then(res => {
    if(res.data?.length>0){
      form.value.checkedIds = res.data.map(item => item.resourcesID);
    }
    setTimeout(() => {
           checkStrictly.value = false; //再打开关联联动
    }, 200);
  })
}


/** 根据角色ID查询部门树结构 */
function getDeptTree(roleId) {
 return deptTreeSelect(roleId).then(response => {
   deptOptions.value = response.depts;
   return response;
 });
}

/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value, type) {
 if (type == "menu") {
   let treeList = menuOptions.value;
   for (let i = 0; i < treeList.length; i++) {
     menuRef.value.store.nodesMap[treeList[i].id].expanded = value;
   }
 } else if (type == "dept") {
   let treeList = deptOptions.value;
   for (let i = 0; i < treeList.length; i++) {
     deptRef.value.store.nodesMap[treeList[i].id].expanded = value;
   }
 }
}

/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value, type) {
 if (type == "menu") {
   menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
 } else if (type == "dept") {
   deptRef.value.setCheckedNodes(value ? deptOptions.value : []);
 }
}

/** 树权限（父子联动） */
function handleCheckedTreeConnect(value, type) {
 if (type == "menu") {
   form.value.menuCheckStrictly = value ? true : false;
 } else if (type == "dept") {
   form.value.deptCheckStrictly = value ? true : false;
 }
}

/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
 // 目前被选中的菜单节点
 let checkedKeys = menuRef.value.getCheckedKeys();
 
 // 半选中的菜单节点
 let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
 checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
 return checkedKeys;
}

/** 提交按钮 */
function submitForm() {
 proxy.$refs["roleRef"].validate(valid => {
   if (valid) {
     if (form.value.id) {
      proxy.API.EditRole({
         ...form.value,
         systemID:value.value,
       }).then(response => {
        // 新增角色路由
          let page_right = [];
          let list = getMenuAllCheckedKeys();
          if(list?.length>0){
            page_right = list.map(item => {
              return { id:0, resourceID:item, rights:[0,1,2,3,4,5,6,7,8,9]} 
            })
          }
          form.value.checkedIds = [];
          form.value.checkedIds = page_right;
          // 增加 删除 修改 都是覆盖操作
          const parm = { roleID:form.value.id, page_right:page_right }
          proxy.API.EditRoleMenus(parm).then(response => {
              proxy.$modal.msgSuccess("修改成功");
              open.value = false;
              getList();
          })
        })
     } else {
      proxy.API.AddRole({
        ...form.value,
        systemID:value.value,
      }).then(response => {
         proxy.$modal.msgSuccess("新增成功");
         open.value = false;
         getList();
       });
     }
   }
 });
}
// 复制
async function copy(text){
 console.log(text);
 try {
   await navigator.clipboard.writeText(text);
   proxy.$modal.msgSuccess('复制成功');
 } catch (err) {
   console.log(err);
   
 }
}

/** 取消按钮 */
function cancel() {
 open.value = false;
 reset();
}

/** 选择角色权限范围触发 */
function dataScopeSelectChange(value) {
 if (value !== "2") {
   deptRef.value.setCheckedKeys([]);
 }
}

/** 提交按钮（数据权限） */
function submitDataScope() {
 if (form.value.roleId != undefined) {
   form.value.deptIds = getDeptAllCheckedKeys();
   dataScope(form.value).then(response => {
     proxy.$modal.msgSuccess("修改成功");
     openDataScope.value = false;
     getList();
   });
 }
}

/** 取消按钮（数据权限）*/
function cancelDataScope() {
 openDataScope.value = false;
 reset();
}
getList();
</script>
<style lang="scss" scoped>
::v-deep(.el-select__icon){
  color: #409EFF;
}
</style>